//
//  HMRefreshing.swift
//  WeiBoXR
//
//  Created by acer on 16/9/26.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
enum HMRefreshControlState {
    case pulling
    case normal
    case refreshing
}
private let HMRefreshControlHeight : CGFloat = 44
class HMRefreshing: UIControl {

    var currentScrollView: UIScrollView?

    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor.gray
        label.textAlignment = .center
        label.text = "下拉刷新"
        return label
        
    }()

    var hmstate : HMRefreshControlState = .normal {
        didSet {
            switch hmstate {
            case .normal:
                iconImageView.isHidden = false
                indicatorView.stopAnimating()
                UIView.animate(withDuration: 0.25, animations: { 
                    self.iconImageView.transform = CGAffineTransform.identity
                    
                })
                messageLabel.text = "下拉刷新"
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.currentScrollView?.contentInset.top -= HMRefreshControlHeight
                    })
                }
            case .pulling:
                UIView.animate(withDuration: 0.25, animations: { 
                    self.iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                messageLabel.text = "松手刷新"
            case .refreshing:
                iconImageView.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新..."
            default:
                break
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI()  {
        backgroundColor = UIColor.red
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)

        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: iconImageView, attribute: .trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: iconImageView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))

    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        guard let scrollview  = newSuperview as? UIScrollView else {
            return
        }
        self.frame.size = CGSize(width: ScreenWidth, height: HMRefreshControlHeight)
        self.frame.origin.y = -HMRefreshControlHeight
//        [.new,.old]
        scrollview.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        currentScrollView = scrollview
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//        print(currentScrollView?.contentOffset.y)
        let contentOffsetY = currentScrollView?.contentOffset.y
        let maxY = -((currentScrollView?.contentInset.top)! + HMRefreshControlHeight)
        if (currentScrollView?.isDragging)! {
            if maxY > contentOffsetY! && hmstate == .normal {
                hmstate = .pulling
                print("松手就刷新puling")

            } else if maxY <= contentOffsetY! && hmstate == .pulling {
                hmstate = .normal
                print("下拉刷新normal")
            
            }
        } else {
            if hmstate == .pulling {
                hmstate = .refreshing
                print("正在刷新")
                UIView.animate(withDuration: 1, animations: { 
                    self.currentScrollView?.contentInset.top += HMRefreshControlHeight
                })
                sendActions(for: .valueChanged)
            }
            
        }

    }
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    func endRefreshing() {
        hmstate = .normal
    }
}
